const express = require('express')

const app = express()

// 模板引擎
const nunjucks = require('nunjucks')
nunjucks.configure(`${__dirname}/views`, { autoescape: true })

// 静态资源中间件
app.use(express.static(`${__dirname}/tools`))

// 搜素页面
app.get('/search', (_, res) => {
  res.setHeader('Content-Type', 'text/html;charset=utf-8')
  res.send(nunjucks.render('search.html'))
})

// query 传参方式  http://127.0.0.1/query?id=1
app.get('/query', (req, res) => {
  const { id } = req.query
  if (id != 1) {
    return res.send({
      code: 0,
      msg: "查询失败",
      data: null
    })
  }
  res.send({
    code: 1,
    msg: "查询成功",
    data: {
      username: '佩华',
      hobby: ['抽烟', '喝酒', '烫头', '蹦迪']
    }
  })
})

// path 传参方式  http://127.0.0.1/path/2
app.get('/path/:id', (req, res) => {
  const { id } = req.params
  if (id != 2) {
    return res.send({
      code: 0,
      msg: "查询失败",
      data: null
    })
  }
  res.send({
    code: 1,
    msg: "查询成功",
    data: {
      username: '向阳',
      hobby: ['抽烟', '喝酒', '烫头', '蹦迪']
    }
  })
})

app.listen(80, () => {
  console.log('express server running at http://127.0.0.1')
})